const fs = require('fs');
// 读取./docs/doc/front目录下的所有文件
fs.readdir('../../docs/doc/front', (err, files) => {
  if (err) {
    console.error(err);
    return;
  }
  // 过滤掉README.md文件并去掉文件名的后缀
  const fileNames = files.filter(file => file !== 'README.md').map(file => file.replace('.md', ''));
  // 读取./docs/.vuepress/config.js文件
  fs.readFile('../../docs/.vuepress/config.js', 'utf8', (err, data) => {
    if (err) {
      console.error(err);
      return;
    }
    const config = eval(`(${data.slice(0, data.length - 1)})`)
    // 将第一个children的值替换为新的数组
    config.themeConfig.sidebar['/doc/front/'][0].children = fileNames;
    // 将修改后的config对象转换为字符串
    const updatedConfig = `module.exports = ${JSON.stringify(config, null, 2)};`;
    // 将修改后的config写入config.js文件
    fs.writeFile('../../docs/.vuepress/config.js', updatedConfig, 'utf8', err => {
      if (err) {
        console.error(err);
        return;
      }
      back().then(res => {
        utils();
      });
    });
  });
});
async function back(){
  await fs.readdir('../../docs/doc/back', (err, files) => {
    if (err) {
      console.error(err);
      return;
    }
    const fileNames = files.filter(file => file !== 'README.md').map(file => file.replace('.md', ''));
    fs.readFile('../../docs/.vuepress/config.js', 'utf8', (err, data) => {
      if (err) {
        console.error(err);
        return;
      }
      const config = eval(`(${data.slice(0, data.length - 1)})`)
      config.themeConfig.sidebar['/doc/back/'][0].children = fileNames;
      const updatedConfig = `module.exports = ${JSON.stringify(config, null, 2)};`;
      fs.writeFile('../../docs/.vuepress/config.js', updatedConfig, 'utf8', err => {
        if (err) {
          console.error(err);
          return;
        }
      });
      console.log('配置文件文件已更新');
    });
  });
}
function utils(){
  fs.readdir('../../docs/doc/utils', (err, files) => {
    if (err) {
      console.error(err);
      return;
    }
    const fileNames = files.filter(file => file !== 'README.md').map(file => file.replace('.md', ''));
    fs.readFile('../../docs/.vuepress/config.js', 'utf8', (err, data) => {
      if (err) {
        console.error(err);
        return;
      }
      const config = eval(`(${data.slice(0, data.length - 1)})`)
      config.themeConfig.sidebar['/doc/utils/'][0].children = fileNames;
      const updatedConfig = `module.exports = ${JSON.stringify(config, null, 2)};`;
      fs.writeFile('../../docs/.vuepress/config.js', updatedConfig, 'utf8', err => {
        if (err) {
          console.error(err);
          return;
        }
      });
      console.log('配置文件文件已更新');
    });
  });
}